/**
 * Response object converts server response XML data to JSON.
 * 
 * @author Andrey Anisimov <hercules@inbox.ru>
 */

class Response {
	
	/**
	 * Constructs new response object.
	 * 
	 * @param root (Node) response root element
	 */
	this.Response = function(root) {
		Response.convert(root, this);
	}
}

/**
 * @protected
 * Returns boolean value from node.
 * 
 * @param node (Node) data node
 * @return bool
 */
Response.getBool = function(node) {
	return ('1' == node.firstChild.nodeValue);
}

/**
 * @protected
 * Returns integer value from node.
 * 
 * @param node (Node) data node
 * @return int
 */
core.ajax.Response.getInt = function(node) {
	return parseInt(node.firstChild.nodeValue);
}

/**
 * @protected
 * Returns floating value from node.
 * 
 * @param node (Node) data node
 * @return float
 */
core.ajax.Response.getFloat = function(node) {
	return parseFloat(node.firstChild.nodeValue);
}

/**
 * @protected
 * Returns array from node.
 * 
 * @param node (Node) data node
 * @return array
 */
Response.getArray = function(node) {
	var arr = new Array();
	for (var i = 0; i < node.childNodes.length; i++) {
		if (node.childNodes.item(i).nodeType == 1) {
			arr.push(this.getValue(node.childNodes.item(i)));
		}
	}
	return arr;
}

/**
 * @protected
 * Returns object from node.
 * 
 * @param node (Node) data node
 * @return object
 */
Response.getObject = function(node) {
	var obj = new Object();
	this.convert(node, obj);
	return obj;
}

/**
 * @protected
 * Returns string value from node.
 * 
 * @param node (Node) data node
 * @return string
 */
Response.getString = function(node) {
	try {
		return node.firstChild.nodeValue;
	} catch (e) {
		return '';  // Empty string case
	}
}

/**
 * @protected
 * Returns value from source node.
 * 
 * @param node (Node) data node
 * @return variant
 */
Response.getValue = function(node) {
	var attr = node.attributes.getNamedItem('type');
	var type = (attr) ? attr.nodeValue : 'string';
	switch (type) {
		case 'null':	return null;
		case 'bool':	return this.getBool(node);
		case 'int':		return this.getInt(node);
		case 'float':	return this.getFloat(node);
		case 'array':	return this.getArray(node);
		case 'object':	return this.getObject(node);
		default:		return this.getString(node);
	}
}

/**
 * @protected
 * Converts node data to object notation.
 * 
 * @param node (Node) data node
 * @param obj (object) object to store a data
 */
core.ajax.convert =
Response.convert = function(node, obj) {
	for (var i = 0; i < node.childNodes.length; i++) {
		if (node.childNodes.item(i).nodeType == 1) {
			var child = node.childNodes.item(i);
			var name = child.nodeName;
			obj[name] = this.getValue(child);
		}
	}
}